package action.listener;

import java.awt.Point;
import java.awt.event.MouseEvent;

import javax.swing.event.MouseInputAdapter;

import undoredo.AbstractCommand;
import undoredo.MoveCommand;
import engine.Vertex;
import gui.Frame;
import gui.View;

public class MoveListener extends MouseInputAdapter
{
   private int active = 1;
   private boolean drag= false;
   private Point restore, point;
   private Vertex v = null;
   private View view;

   public MoveListener(View view)
   {
      super();
      this.view = view;
   }

   public Vertex getActiveVertex()
   {
      for (int i = 0; i < view.getVertices().size(); i++)
         if (view.getVertices().get(i).getStatus() == active)
            return view.getVertices().get(i);
      return null;
   }

   @Override
   public void mouseDragged(MouseEvent e)
   {
      // TODO Auto-generated method stub
      if (view.getSelectStatu())
      {
         if ((v = getActiveVertex()) != null)
         {
            //            restore=v.getPoint();
            point=e.getPoint();
            v.setPosition(e.getX(), e.getY());

            view.setSelection(v.xPos() - 15, v.yPos() - 15, 30, 30);
            drag=true;
         }
         view.repaint();
      }

   }
   @Override
   public void mouseMoved(MouseEvent e)
   {
      // TODO Auto-generated method stub
      if (v != null)
      {
         v.setStatus(v.getRecentStatus());
         v = null;
      }
      drag=false;

   }
   @Override
   public void mousePressed(MouseEvent e)
   {
      restore= e.getPoint();
   }
   @Override
   public void mouseReleased(MouseEvent e)
   {

      if(drag==true)
      {
         AbstractCommand command = new MoveCommand(v, restore, point);
         command.execute();
         Frame.addCommandToStack(command);
         Frame.setUndoRedoVisible();
         view.repaint();
      }
   }


}
